package com.zhuangjie.order.mq.consumer.listener.delay;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhuangjie.order.entity.Order;
import com.zhuangjie.order.enums.OrderState;
import com.zhuangjie.order.mq.producer.structure.OrderMQStructure;
import com.zhuangjie.order.service.OrderService;
import com.zhuangjie.rabbit.listen.wrap.MQListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class OrderCancelDelayMQListener extends MQListener<Long> {
    @Autowired
    private OrderService orderService;

    @Override
    public String listenQueue() {
        return OrderMQStructure.Queues.ORDER_CANCEL_QUEUE;
    }

    @Override
    public void onMessageArrives(Long orderId) throws Exception {
        log.info("Order监听器/消费者,已接到需要进行订单取消的订单编号：{}",orderId);
        // 先查询订单是否已经取消，如果已经取消，那就不用进行下面的操作了，因为用户可能早已主动取消
        long count = orderService.count(Wrappers.lambdaQuery(Order.class)
                .eq(Order::getId, orderId)
                .eq(Order::getState, OrderState.WAITING_FOR_PAYMENT));
        if (count == 0) return;
        // 如果还没取消，那就进行取消操作
        orderService.cancelOrderForMQ(orderId,"超时未支付");
    }
}
